<?php

App::uses('AppModel', 'Model');

class Member extends AppModel {
	
	public $name = "Member";
	public $useTable = "members";
	public $order = "Member.firstname ASC, Member.surname ASC";
	
	public $validate = array(
		'firstname' => array('rule' => 'notEmpty', 'message' => STR_REQUIRED_FIELD),
		'surname' => array('rule' => 'notEmpty', 'message' => STR_REQUIRED_FIELD)
	);
	
	public $hasMany = array(
		'MemberContact' => array(
			'foreignKey' => 'member_id'
		),
		'MemberChoir' => array(
			'foreignKey' => 'member_id',
			'order' => 'MemberChoir.date_from DESC'
		),
		'MemberChoirFunction' => array(
			'foreignKey' => 'member_id'
		)
	);
	
	public $hasOne = array(
		'MemberFather' => array(
			'className' => 'MemberParent',
			'foreignKey' => 'member_id',
			'conditions' => array('MemberFather.type' => 'father')
		),
		'MemberMother' => array(
			'className' => 'MemberParent',
			'foreignKey' => 'member_id',
			'conditions' => array('MemberMother.type' => 'mother')
		)
	);
    
    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
        
        $this->virtualFields['name'] = "CONCAT({$this->alias}.firstname, \" \", {$this->alias}.surname)";
    }
	
	public function afterFind($results, $primary) {
		if ($primary) {
    		foreach($results as &$result) {
    		    
    			$r = &$result["Member"];
    			if(!$r) continue;
    			
    			$r['choir_sex'] = array();
    			
    			if((int)$r["choir_sex_male"]>0) $r["choir_sex"][] = "male";
    			if((int)$r["choir_sex_female"]>0) $r["choir_sex"][] = "female";
    			if((int)$r["choir_sex_mixed"]>0) $r["choir_sex"][] = "mixed";
    			
    			if(empty($r["choir_sex"])) {
    			    $r["choir_sex"] = array("mixed");
    			}
    		}
		}
		
		return $results;
	}
	
	public function refactorData($data = null) {
		if($data) {
			$this->set($data);
		}
		
		if($this->data) {
			// refactor Contacts
			if(!empty($this->data['MemberContact'])) {
				$tmp = array();
				foreach($this->data['MemberContact']['contact_type'] as $k=>$v) {
					$tmp[$k]['contact_type'] = $v;
					$tmp[$k]['contact_value'] = $this->data['MemberContact']['contact_value'][$k];
				}
				$this->data['MemberContact'] = $tmp;
			}
			
			// refactor Choirs
			if(!empty($this->data['MemberChoir'])) {
				$tmp = array();
				foreach($this->data['MemberChoir']['choir'] as $k=>$v) {
					$tmp[$k]['choir'] = $v;
					$tmp[$k]['date_from'] = $this->data['MemberChoir']['date_from'][$k];
					$tmp[$k]['date_to'] = $this->data['MemberChoir']['date_to'][$k];
					$tmp[$k]['active'] = (int)@$this->data['MemberChoir']['active'][$k];
				}
				$this->data['MemberChoir'] = $tmp;
			}
		}
	}
	
	public function deleteRelationsData($id=null) {
		if($id) {
			$this->id = $id;
		}
		if($this->id) {
			$this->MemberContact->query("DELETE FROM member_choirs WHERE member_id = " . $this->id);
			$this->MemberContact->query("DELETE FROM members_functions WHERE member_id = " . $this->id);
			$this->MemberContact->query("DELETE FROM member_contacts WHERE member_id = " . $this->id);
			$this->MemberContact->query("DELETE FROM member_parents WHERE member_id = " . $this->id);
		}
	}
	
	public function getConditionsForFilter($filter) {
	    $c = array();
	    if (! empty($filter)) {
	        $kword = $filter['keyword'];
	        unset($filter['keyword']);
	        
	        if (! empty($kword)) {
	            $c = array(
                    'CONCAT_WS(\' \', Member.firstname, Member.surname) LIKE' => "%{$kword}%"
	            );
	        }
	        
    	    if (self::isAdvancedSearch($filter)) {
    	        $c = array();
    	        
    	        if (! empty($filter['name']))
    	            $c['CONCAT_WS(\' \', Member.firstname, Member.surname) LIKE'] = "%".$filter['name']."%";
    	        
    	        if (! empty($filter['registration_date']['from']) &&
    	            ! empty($filter['registration_date']['to']) )
    	            $c[] = array(
	                    'Member.registration_date >=' => $filter['registration_date']['from'],
	                    'Member.registration_date <=' => $filter['registration_date']['to']
    	            );
    	        
    	        if (! empty($filter['category']))
    	            $c['Member.category'] = $filter['category'];
    	        
    	        if (! empty($filter['voice']))
    	            $c['Member.voice'] = $filter['voice'];
    	        
    	        if (! empty($filter['choir_sex_mixed']))
    	            $c['Member.choir_sex_mixed'] = $filter['choir_sex_mixed'];
    	        if (! empty($filter['choir_sex_male']))
    	            $c['Member.choir_sex_male'] = $filter['choir_sex_male'];
    	        if (! empty($filter['choir_sex_female']))
    	            $c['Member.choir_sex_female'] = $filter['choir_sex_female'];
    	        
    	        if (! empty($filter['function']))
    	            $c['Function.name'] = $filter['function'];
    	        
    	        if (! empty($filter['education']))
    	            $c['Member.education'] = $filter['education'];
    	        
    	        if (! empty($filter['birthday']['from']) &&
    	        ! empty($filter['birthday']['to']) )
    	            $c[] = array(
    	                    'Member.birthday >=' => $filter['birthday']['from'],
    	                    'Member.birthday <=' => $filter['birthday']['to']
    	            );
    	        
    	        if (! empty($filter['passport_number'])) {
    	            if ($filter['passport_number'] > 0) {
        	            $c['Member.passport_number NOT'] = array('NULL', '');
    	            } else {
    	                $c['Member.passport_number'] = array('NULL', '');
    	            }
    	        }
    	        
    	        if (! empty($filter['passport_country']))
    	            $c['Member.passport_country LIKE'] = '%' . $filter['passport_country'] . '%';
	        }
	    }
	    
	    return $c;
	}
	
	public static function isAdvancedSearch($filter) {
	    $ret = false;
	    
	    if (! empty($filter)) {
            foreach ($filter as $k=>$v) {
                if (is_array($v)) {
                    $in = false;
                    foreach ($v as $kk=>$vv) {
                        if (!empty($vv)) {
                            $ret = true;
                            break;
                        }
                    }
                    if ($in) break;
                } else if ($k!='keyword' && !empty($v)) {
                    $ret = true;
                    break;
                }
            }
	    }
	    
	    return $ret;
	}
}